package bainuo

import com.alibaba.fastjson.JSON
import groovy.sql.Sql

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

def execute() {
    def conn
    def conn2
    try {
        // 初始化数据库连接
        conn2 = groovy.sql.Sql.newInstance(mypara.hqcon(1))
        conn = groovy.sql.Sql.newInstance(mypara.hqcon(2))

        // 获取当前日期时间并格式化
        def now = LocalDateTime.now()
        def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        def formattedDateTime = now.format(formatter)
        def selectSql = "select * from WMS_time where type = '待接收物料' "
        def NOWtime = conn2.firstRow(selectSql)

        // 查询 po_arriveorder 表
        def sql1 = "SELECT pk_arriveorder, vbillcode, ctrantypeid, pk_supplier, bisback, pk_pupsndoc, pk_dept_v,creationtime, modifiedtime FROM po_arriveorder where fbillstatus=3 and dr=0 "
        // 获取 po_arriveorder 表的数据
        def dhList = conn.rows(sql1,[NOWtime.updateTime,formattedDateTime])
        println(sql1)
        processDataInBatches(dhList, 500, conn);

        // 插入时间记录
        def sqlTime = "UPDATE WMS_time set updateTime = ? where type = ?"
        conn2.execute(sqlTime, [ formattedDateTime,'待接收物料'])
    } catch (Exception e) {
        e.printStackTrace()
    } finally {
        if (conn != null) {
            conn.close()
        }
        if (conn2 != null) {
            conn2.close()
        }
    }
}

// 按批次处理数据
def processDataInBatches(def data, int batchSize, def conn) {
    for (int i = 0; i < data.size(); i += batchSize) {
        // 获取当前批次的子列表
        List<String> batch = data.subList(i, Math.min(i + batchSize, data.size()));
        // 调用处理方法
        processBatch(batch, conn);
    }
}

def processBatch(def dhList, def conn){
    List<Map<String, Object>> results = new ArrayList<>()
    // 组装 JSON 数据
    for (def dhitem : dhList) {
        if (dhitem != null) {
            // 查询 bd_psndoc 表
            def cgSql4 = conn.firstRow("select name from bd_psndoc where pk_psndoc = ?", [dhitem.pk_pupsndoc]) ?: [:]
            String bussUserName = cgSql4?.name ?: ""

            // 查询 org_dept 表
            def bmList = conn.firstRow("select name from org_dept_v where pk_dept = ?", [dhitem.pk_dept_v]) ?: [:]
            String constrCorpId = bmList?.name ?: ""

            // 查询 bd_supplier 表
            def gyList = conn.firstRow("select code,name from bd_supplier where pk_supplier = ?", [dhitem.pk_supplier]) ?: [:]
            String supName = gyList?.code ?: ""

            Map<String, Object> bill = new HashMap<>()
            bill.put("id", dhitem.pk_arriveorder) // 到货单id
            bill.put("billNo", dhitem.vbillcode) // 到货单编号
            bill.put("billName", dhitem.vbillcode) // 到货单名称
            bill.put("supName", supName) // 供应商名称
            bill.put("billType", "采购入库") // 到货类型
            bill.put("bussUserName", bussUserName) // 采购员名称
            bill.put("creationtime",dhitem.creationtime);
            bill.put("modifiedtime",dhitem.modifiedtime);
            if (dhitem.bisback == "Y") {
                bill.put("redBillFlag", 1)
            } else {
                bill.put("redBillFlag", 0)
            }// 是否退货
            bill.put("constrCorpId", constrCorpId) // 采购部门名称
            List<Map<String, Object>> items = new ArrayList<>()

//                def sql2 = "SELECT pk_arriveorder_b, norigtaxprice, nnum, nastnum, cunitid, castunitid, vbatchcode, nastnum, castunitid, pk_srcmaterial, vchangerate, cprojectid, csourcetypecode, cproductorid, dproducedate, dinvaliddate, vmemob, pk_material FROM po_arriveorder_b WHERE  pk_arriveorder = ?"

            // 查询 po_arriveorder_b 表
            def sql2 = "SELECT p.pk_arriveorder_b,p.norigtaxprice,p.nnum,p.nastnum,p.cunitid,p.castunitid,p.vbatchcode,p.pk_srcmaterial,p.vchangerate,p.cprojectid,p.csourcetypecode,p.cproductorid,p.dproducedate,p.dinvaliddate,p.vmemob,p.pk_material FROM po_arriveorder_b p left join bd_material_v mv on p.pk_material=mv.pk_material left join bd_marbasclass mc on mc.pk_marbasclass=mv.pk_marbasclass WHERE mc.def2='true' and p.pk_arriveorder = ?"
            def qitems = conn.rows(sql2, [dhitem.pk_arriveorder])

            for (def det : qitems) {
                // 查询 bd_material 表
                def wuliao = conn.firstRow("select pk_material, code, name, materialtype, materialspec, def9, def7, pk_marbasclass, materialshortname from bd_material where pk_material = ?", [det.pk_material]) ?: [:]

                // 查询 bd_measdoc 表
                def danwei1 = conn.firstRow("select pk_measdoc, code, name from bd_measdoc where pk_measdoc = ?", [det.cunitid])
                def danwei2 = conn.firstRow("select pk_measdoc, code, name from bd_measdoc where pk_measdoc = ?", [det.castunitid])

                // 查询 bd_marbasclass 表
                def fenlei = conn.firstRow("select name,def2 from bd_marbasclass where pk_marbasclass = ?", [wuliao.pk_marbasclass]) ?: [:]
                if (fenlei.def2 != "true"){
                    continue
                }
                String categoryDesc = fenlei?.name ?: ""

                // 查询 bd_project 表
                def xiangmu = conn.firstRow("select project_code from bd_project where pk_project = ?", [det.cprojectid]) ?: [:]
                String projectNo = xiangmu?.project_code ?: ""

                // 查询 bd_defdoc 表
                def changshang = conn.firstRow("select name from bd_defdoc where pk_defdoc = ?", [det.cproductorid]) ?: [:]
                String manufacturer = changshang?.name ?: ""

                // 查询 bd_materialplan 表
                def zdkuList = conn.firstRow("select safetystocknum from bd_materialplan where pk_material = ?", [wuliao.pk_material]) ?: [:]
                int lowLimitWarningValue = zdkuList?.safetystocknum ?: 0

                // 将 vchangerate 转换为浮点数
                def parts = det.vchangerate.split('/')
                def numerator = parts[0].toBigDecimal()
                def denominator = parts[1].toBigDecimal()
                def packageNum = numerator / denominator

                Map<String, Object> item = new HashMap<>()
                item.put("id", det.pk_arriveorder_b) // 到货单明细行id
                item.put("batchNo", det.vbatchcode) // 批号
                item.put("categoryDesc", categoryDesc) // 物料类型
                item.put("itemNo", wuliao.code ?: "") // 物料代码
                item.put("itemName", wuliao.name ?: "") // 物料名称
                item.put("itemAlias", wuliao.materialshortname ?: "") // 物料别名
                item.put("itemCustomName", wuliao.materialshortname ?: "") // 自定义名称
                item.put("itemModel", wuliao.materialtype ?: "") // 型号
                item.put("itemSpec", wuliao.materialspec ?: "") // 包装规格
                item.put("cas", wuliao.def9 ?: "") // cas
                item.put("applyNum", det.nastnum) // 到货辅助数量
                item.put("unit", danwei2.name) // 辅助计量单位
                item.put("purchaseNum", det.nnum) // 最小单位数量
                item.put("packageUnit", danwei1.name) // 最小计量单位
                item.put("applyPrice", det.norigtaxprice) // 单价
                item.put("unPurchaseNum", 0) // 最小单位未到货数量
                item.put("packageNum", packageNum) // 辅助转换率
                item.put("lowLimitWarningValue", lowLimitWarningValue) // 低限预警值
                item.put("storageConditions", wuliao.def7 ?: "") // 贮存条件
                item.put("projectNo", projectNo) // 项目代号
                item.put("itemSource", "外购") // 物料来源
                item.put("manufacturer", manufacturer) // 生产厂家
                item.put("manufacturerDate", det.dproducedate?.format('yyyy-MM-dd')) // 生产日期
                item.put("expectPeriodValidity", det.dinvaliddate?.format('yyyy-MM-dd')) // 有效期
                item.put("remarks", det.vmemob ?: "") // 备注
                item.put("status", "合格") // 状态
                items.add(item)
            }

            Map<String, Object> root = new HashMap<>()
            root.put("bill", bill)
            root.put("item", items)
            results.add(root)
        }
    }

    // 准备最终的数据结构
    Map<String, List> pushData = new HashMap<>()
    pushData.put("items", results)

    // 调用 start 方法
    WMS_daohuodan(pushData)  // 假设 start 方法接受一个 Map<String, List>
}
def WMS_daohuodan(items){
    Https.httpFWToMap("http://10.1.1.226:8099/wsdsjmcloud-v12/wbs/funcexe3/WMS_daijieshouwuliao001",items)
}
class Https{
    public static HashMap<String, Object> account = new HashMap<String, Object>();

    public Https() {
    }

    public Https(HashMap<String, Object> account) {
        this.account = account;
    }

    public static Map httpFWToMap(String url, Map mapdata) {
        String json = JSON.toJSONString(mapdata);
        println "请求JSON"
        println json
        //PrintWriter out = null;
//        DataOutputStream out
        OutputStream out
        BufferedReader ins = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");

            conn.connect();

            out = conn.getOutputStream();
            if (!"".equals(json)) {
                //out.writeBytes(json);
                out.write(json.getBytes("UTF-8"));
            }
            out.flush();
            out.close();


            // 定义BufferedReader输入流来读取URL的响应
            //            ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            if (conn.getResponseCode() == 200) {
                ins = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            } else {
                ins = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
            }

            String line;
            while ((line = ins.readLine()) != null) {
                result += line;
            }
            println("调用WMS返回报文=" + result)
            return JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("[POST请求]向地址：" + url + " 发送数据：" + json + " 发生错误!" + result + "JSON结束");
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException ex) {
                System.out.println("关闭流异常");
            }
        }
        return null;
    }
}